package beavers.studio.golfberry;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import beavers.studio.golfberry.model.GolfBerryData;

import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.util.Persistable;

public class FileManager implements Persistable {

	private static final long 	PS_KEY 		= 0x19a299fa10f89a5bL;
	private static final String ROOT_PATH	= "file:///store/golfberry/";
	private static final String IMAGE_PATH	= ROOT_PATH + "img/";
	
	//Singleton skeleton
	private static FileManager _inst;
	public static FileManager inst() {
		if(_inst == null) _inst = new FileManager();
		return _inst;
	}
	
	public FileManager() {
		//Open persistent object
		_po = PersistentStore.getPersistentObject(PS_KEY);
		
		//Create app directory
		FileConnection fcon = null;
		try {
			fcon = (FileConnection) Connector.open(ROOT_PATH);
			if(!fcon.exists()) fcon.mkdir();
			fcon = (FileConnection) Connector.open(IMAGE_PATH);
			if(!fcon.exists()) fcon.mkdir();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fcon.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void commitGolfBerryData(GolfBerryData data) {
		_po.setContents(data);
		_po.commit();
	}
	
	public GolfBerryData getGolfBerryData() {
		return (GolfBerryData) _po.getContents();
	}
	
	public boolean saveImage(byte[] data, String filename) {
		//Prepare vars
		FileConnection 	fcon 	= null;
		OutputStream 	os 		= null;
		
		//Saving file...
		try {
			fcon = (FileConnection) Connector.open(IMAGE_PATH + filename);
			if(fcon.exists()) return false;
			fcon.create();
			os = fcon.openOutputStream();
			os.write(data);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		
		//Close stream
		if(os!=null) 	try { os.close(); } catch (Exception e) { e.printStackTrace(); }
		if(fcon!=null)	try { fcon.close(); } catch (Exception e) { e.printStackTrace(); }
		
		//Save succeed
		return true;
	}
	
	public byte[] loadImage(String filename) {
		//Prepare vars
		FileConnection 	fcon 	= null;
		InputStream 	is 		= null;
		byte[] 			data	= null;
		
		//Read file...
		try {
			fcon = (FileConnection) Connector.open(IMAGE_PATH + filename);
			if(!fcon.exists()) return null;
			is = fcon.openInputStream();
			data = new byte[(int)fcon.fileSize()];
			is.read(data);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
		//Close stream
		if(is!=null) 	try { is.close(); } catch (Exception e) { e.printStackTrace(); }
		if(fcon!=null)	try { fcon.close(); } catch (Exception e) { e.printStackTrace(); }
		
		//Return
		return data;
	}
	
	private PersistentObject _po;
}
